<template>
  <div class="article-detail">
    <div class="text-center" v-if="loading">文章加载中...</div>
    <div class="text-center" v-if="articleError">文章加载失败，或者文章不存在</div>
    <template v-if="info">
      <div class="article-title"><span>{{info.title}}</span></div>
      <div class="article-info">
        <div class="span">
          <i class="iconfont icon-shijian"></i>{{info.updateAt | formatDate}}
        </div>
        <div class="span">
          <i class="iconfont icon-jushoucang"></i>{{info.numbers.like}}
        </div>
        <div class="span">
          <i class="iconfont icon-pinglun"></i>{{info.numbers.comment}}
        </div>
          <div class="span">
          <i class="iconfont icon-read"></i>{{info.numbers.look}}
        </div>
        <router-link class="span cur"  target="_blank" :to="'/editor?id='+ info._id">编辑</router-link>
      </div>
      <div class="content-html markdown-body" v-html="info.content"></div>
      <div class="article-tags">
        <router-link :to="`/article?tag=${v._id}`" v-for="v in info.tags" :key="v._id"># {{v.name}}</router-link>
      </div>
      <div class="page">
        <router-link v-if="info.prev" :to="`/article/${info.prev._id}`">上一篇 : {{info.prev.title}}</router-link>
        <span v-else></span>
        <router-link v-if="info.next" :to="`/article/${info.next._id}`">下一篇 : {{info.next.title}}</router-link>
        <span v-else></span>
      </div>
      <!--评论部分-->
      <div class="comments">
        <div class="title"><span>评 论</span></div>
        <!--评论文章-->
        <div class="comment-text">
          <textarea class="textarea" maxlength="100" v-model="comments.value"></textarea>
          <div class="operate">
            <div class="left"></div>
            <Button @click="addComment" :loading="addLoading">评论</Button>
          </div>
        </div>
        <div class="comment-list">
          <div class="comment-item" v-for="(v, index) in comments.list" :key="v._id">
            <!--评论人信息-->
            <div class="user-info">
              <div class="head-img"><img :src="v.auth.headImg" alt=""></div>
              <div class="username">{{v.auth.username}}</div>
            </div>
            <!--评论内容-->
            <div class="content" v-html="v.content"></div>
            <!--操作-->
            <div class="operate">
              <div class="like"><i class="iconfont icon-zan1"></i><span>{{v.numbers.like}}</span></div>
              <div @click="toggleChildrenList(v, index)">{{v.numbers.children}}条评论</div>
              <span>{{v.createAt | relativeTime}}</span>
            </div>
            <!--子评论-->
            <div class="children-comment-list" v-show="v.children.show">
              <div>
                <div class="comment-item" v-for="c in v.children.list" :key="c._id">
                  <div class="user-info">
                    <div class="head-img"><img :src="c.auth.headImg" alt=""></div>
                    <div class="username">{{c.auth.username}}</div>
                  </div>
                  <div class="content" v-html="c.content"></div>
                  <div class="operate">
                    <span>{{c.createAt | relativeTime}}</span>
                    <div class="hf">回复</div>
                    <div class="del" @click="removeChildrenComment(v, c._id)">删除</div>
                  </div>
                </div>
              </div>
              <!--回复评论输入框-->
              <div class="textarea">
                <input type="text" v-model="v.c_value">
                <Button type="black" @click="addChildrenComment(v)" :loading="v.c_loading">评论</Button>
              </div>
            </div>
          </div>
        </div>
        <div class="text-center" style="margin-top: 20px;" v-if="comments.more">
          <Button :loading="comments.loading" @click="morePage">加载更多</Button>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import Button from '../../components/Button'
import userFormat from '../../assets/js/userFormat'

export default {
  name: 'ArticleDetail',
  data () {
    return {
      info: null,
      loading: true,
      articleError: false,
      articleId: this.$route.params.id,
      comments: {
        value: '',
        list: [],
        loading: false,
        more: true,
        page: 1
      },
      addLoading: false
    }
  },
  watch: {
    async '$route' () {
      this.articleId = this.$route.params.id
      this.comments.list = []
      await this.getInfo()
      this.getCommentsList()
      this.$utils.scrollToTop()
    }
  },
  components: {
    Button
  },
  created () {
    this.getInfo()
    this.getCommentsList()
  },
  mounted () {
  },
  methods: {
    // 获取文章详情
    async getInfo () {
      this.loading = true
      this.articleError = false
      const params = {id: this.$route.params.id}
      try {
        const {data} = await this.$http.get('/v1/article', {params})
        data.content = this.$md.render(data.content)
        this.info = data
      } catch (e) {
        this.$pop.notice({
          title: '获取失败',
          type: 'error'
        })
        this.articleError = true
      }
      this.loading = false
    },
    // 获取评论列表
    async getCommentsList () {
      this.comments.loading = true
      const params = {articleId: this.articleId, page: this.comments.page}
      const {data} = await this.$http.get('/v1/comment', {params})
      for (let i of data.list) {
        i.content = userFormat(i.content)
        i.children = {
          show: false,
          list: [],
          page: 1
        }
        this.comments.list.push(i)
      }
      if (data.list.length < 10) {
        this.comments.more = false
      } else {
        this.comments.more = true
      }
      this.comments.loading = false
    },
    // 显示隐藏子评论
    async toggleChildrenList (item) {
      let children = item.children
      // 深入响应式原理, 动态生成键值对，用于子评论
      const valueArr = ['c_value', 'c_loaing']
      for (let i of valueArr) {
        if (!item[i]) {
          this.$set(item, i, '')
        }
      }
      if (children.show) {
        children.show = false
        return false
      }
      children.show = true
      await this.getChildrenCommentsList(item)
    },
    // 获取子评论列表
    async getChildrenCommentsList (item) {
      let children = item.children
      const params = {commentId: item._id, page: children.page}
      const {data} = await this.$http.get('/v1/commentChildren', {params})
      console.log(data)
      for (let i of data.list) {
        i.content = userFormat(i.content)
      }
      children.list = data.list
    },
    // 添加评论
    async addComment () {
      this.addLoading = true
      const content = this.comments.value.trim()
      const articleId = this.articleId
      try {
        let {data} = await this.$http.post('/v1/comment', {content, articleId})
        data.children = {
          show: false,
          list: [],
          page: 1
        }
        this.comments.value = ''
        this.info.numbers.comment += 1
        this.comments.list.unshift(data)
      } catch (e) {
        this.$pop.notice({
          title: '评论失败',
          type: 'error'
        })
      }
      this.addLoading = false
    },
    // 添加子评论
    async addChildrenComment (item, index) {
      item.c_loading = true
      const articleId = this.articleId
      const commentId = item._id
      const content = item.c_value
      console.log(content)
      await this.$http.post('/v1/commentChildren', {content, articleId, commentId})
      item.c_value = ''
      item.c_loading = false
      await this.getChildrenCommentsList(item)
      item.numbers.children += 1
    },
    // 删除子评论
    async removeChildrenComment (item, id) {
      await this.$http.delete('/v1/commentChildren', {data: {id}})
      await this.getChildrenCommentsList(item)
      item.numbers.children -= 1
    },
    async morePage () {
      this.comments.page += 1
      this.getCommentsList()
    }
  }
}
</script>
